package com.hamilton.erik.pt.mobile.android;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.core.model.Enclosure;
import com.hamilton.erik.pt.core.util.StringUtil;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.JsonUtil;
import com.hamilton.erik.pt.mobile.util.ResultUtil;
import com.hamilton.erik.pt.mobile.util.ServerUtil;

public class ViewEnclosureActivity extends ViewDataActivity {
	
	private Animal animal = null;
	private Enclosure enclosure = null;
	private ProgressDialog progressDialog = null;

	private final int EDIT_ACTIVITY = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_enclosure);
		
		findViewById(R.id.enclosure_view_add_enclosure_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						addEnclosure();
					}
				});
		
		findViewById(R.id.enclosure_view_edit_enclosure_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						edit();
					}
				});

		findViewById(R.id.enclosure_view_view_enclosure_maintenance_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewEnclosureMaintenance();
					}
				});

		findViewById(R.id.enclosure_view_view_enclosure_notes_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewEnclosureNotes();
					}
				});
		
		animal = (Animal)getIntent()
							.getSerializableExtra(
								getString(R.string.extra_animal_object));
		
		if(!TextUtils.isEmpty(animal.getName())) {
			setTitle(animal.getName() + "'s Enclosure");
		};

		retrieve(getIntent());
		populateFields();
	}
	
	protected void retrieve(Intent intent) {
		StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildEnclosurePath());
		url.append("/retrieve/enclosure/").append(animal.getId());

		if (progressDialog == null) {
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle(getString(R.string.progress_loading_title));
	        progressDialog.setMessage(getString(R.string.view_enclosure_progress_retrieving_enclosure));
	    }
	    progressDialog.show();
		
		VolleyJsonRestClient.getClient().getJsonObject(url.toString(),
								new RetrieveEnclosureSuccessListener(),
								new DisplayErrorErrorListener(this, progressDialog));
	}
	
	protected void populateFields() {
		if(enclosure == null || enclosure.getId() == null) {
			// Display the Add button
			findViewById(R.id.enclosure_view_add_enclosure_button).setVisibility(View.VISIBLE);
		}
		else {
			// Remove the display button
			findViewById(R.id.enclosure_view_add_enclosure_button).setVisibility(View.GONE);
			
			// Display everything except the Add button
			findViewById(R.id.enclosure_view_edit_enclosure_button).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_type_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_type_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_shape_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_shape_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_height_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_height_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_length_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_length_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_width_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_width_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_volume_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_volume_field).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_volume_unit_label).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_volume_unit_field).setVisibility(View.VISIBLE);
			
			findViewById(R.id.enclosure_view_view_enclosure_maintenance_button).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_view_enclosure_notes_button).setVisibility(View.VISIBLE);
			
			findViewById(R.id.enclosure_view_separator1).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_separator2).setVisibility(View.VISIBLE);
			findViewById(R.id.enclosure_view_separator3).setVisibility(View.VISIBLE);
			
			// Load the data to the fields
			String temp;
			
			temp = enclosure.getEnclosureType();
			if(!TextUtils.isEmpty(temp)) {
				TextView typeTextView =
					(TextView)findViewById(R.id.enclosure_view_type_field);
				typeTextView.setText(temp);
			}
			
			if(enclosure.getShape() != null) {
				TextView shapeTextView =
					(TextView)findViewById(R.id.enclosure_view_shape_field);
				shapeTextView.setText(enclosure.getShape().toString());
			}

			temp = StringUtil.safeDoubleToString(enclosure.getHeight());
			if(!TextUtils.isEmpty(temp)) {
				TextView heightTextView =
					(TextView)findViewById(R.id.enclosure_view_height_field);
				heightTextView.setText(temp);
			}

			temp = StringUtil.safeDoubleToString(enclosure.getLength());
			if(!TextUtils.isEmpty(temp)) {
				TextView lengthTextView =
					(TextView)findViewById(R.id.enclosure_view_length_field);
				lengthTextView.setText(temp);
			}

			temp = StringUtil.safeDoubleToString(enclosure.getWidth());
			if(!TextUtils.isEmpty(temp)) {
				TextView widthTextView =
					(TextView)findViewById(R.id.enclosure_view_width_field);
				widthTextView.setText(temp);
			}

			temp = StringUtil.safeDoubleToString(enclosure.getVolume());
			if(!TextUtils.isEmpty(temp)) {
				TextView volumeTextView =
					(TextView)findViewById(R.id.enclosure_view_volume_field);
				volumeTextView.setText(temp);
			}

			temp = enclosure.getVolumeUnit();
			if(!TextUtils.isEmpty(temp)) {
				TextView volumeUnitTextView =
					(TextView)findViewById(R.id.enclosure_view_volume_unit_field);
				volumeUnitTextView.setText(temp);
			}
		}
	}
	
	private void addEnclosure() {
		Enclosure newEnclosure;
		if(enclosure == null) {
			newEnclosure = new Enclosure();
			newEnclosure.setAnimalId(animal.getId());
		}
		else {
			newEnclosure = enclosure;
		}
		
		Intent editEnclosureActivity = new Intent(getApplicationContext(), EditEnclosureActivity.class);
		editEnclosureActivity.putExtra(getString(R.string.extra_animal_object), animal);
		editEnclosureActivity.putExtra(getString(R.string.extra_enclosure_object), newEnclosure);
		startActivityForResult(editEnclosureActivity, EDIT_ACTIVITY);
	}
	
	protected void edit() {
		Intent editEnclosureActivity = new Intent(getApplicationContext(), EditEnclosureActivity.class);
		editEnclosureActivity.putExtra(getString(R.string.extra_animal_object), animal);
		editEnclosureActivity.putExtra(getString(R.string.extra_enclosure_object), enclosure);
		startActivityForResult(editEnclosureActivity, EDIT_ACTIVITY);
	}
	
	protected void delete() {
		StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildEnclosurePath());
		url.append("/delete/").append(enclosure.getId());
		
		if (progressDialog == null) {
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle(getString(R.string.progress_deleting_title));
	        progressDialog.setMessage(getString(R.string.view_enclosure_progress_deleting_enclosure));
	    }
	    progressDialog.show();
		
		VolleyJsonRestClient.getClient().deleteJsonObject(url.toString(),
								new DeleteEnclosureSuccessListener(),
								new DisplayErrorErrorListener(this, progressDialog));
	}
	
	private void viewEnclosureMaintenance() {
		Intent viewEnclosureMaintenanceListActivity = new Intent(getApplicationContext(), EnclosureMainteanceListActivity.class);
		viewEnclosureMaintenanceListActivity.putExtra(getString(R.string.extra_animal_object), animal);
		viewEnclosureMaintenanceListActivity.putExtra(getString(R.string.extra_enclosure_object), enclosure);
		startActivity(viewEnclosureMaintenanceListActivity);
	}
	
	private void viewEnclosureNotes() {
		Intent viewEnclosureNotesActivity = new Intent(getApplicationContext(), NoteListActivity.class);
		viewEnclosureNotesActivity.putExtra(getString(R.string.extra_animal_object), animal);
		viewEnclosureNotesActivity.putExtra(getString(R.string.extra_note_reference_id), enclosure.getId());
		viewEnclosureNotesActivity.putExtra(getString(R.string.extra_note_base_rest_path), ServerUtil.getInstance().buildEnclosurePath());
		viewEnclosureNotesActivity.putExtra(getString(R.string.extra_note_title_type), "Enclosure");
		startActivity(viewEnclosureNotesActivity);
	}
	
	private class RetrieveEnclosureSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			enclosure = new Enclosure();
			if (response != null) {
				try {
					
					enclosure = JsonUtil.getInstance().getEnclosure(response);
					
				} catch (Exception e) {
					Log.e("ViewEnclosureActivity", String.format("%s: %s",
							"Failed to convert JSONObject to Enclosure.",
							e.getMessage()));
				}
				
				populateFields();
				
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_enclosure, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			case R.id.action_view_enclosure_edit :
				edit();
				return true;
			case R.id.action_view_enclosure_delete :
				delete();
			default :
				return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == EDIT_ACTIVITY && resultCode == ResultUtil.RESULT_SUCCESS) {
			isEdited = true;
			retrieve(data);
			populateFields();
		}
	}
	
	// Catch the back button(After 2.0)
	@Override
	public void onBackPressed() {
		finishWithResult();
	}

	// Catch the back button(Before 2.0)
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishWithResult();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public void finishWithResult() {
		if(isEdited) {
			setResult(ResultUtil.EDITED);
		}

		finish();		
	}
	
	private class DeleteEnclosureSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			
			setResult(ResultUtil.DELETED, null);
			finish();
		}
	}

}
